package com.css.zfzx.fwsjcj.modules.structure.repository.impl;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.api.local.org.UserAPI;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.division.repository.DivisionRepository;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.PlatformSpringUtils;
import com.css.zfzx.fwsjcj.commen.util.Constant;
import com.css.zfzx.fwsjcj.commen.util.ServerUtil;
import com.css.zfzx.fwsjcj.modules.expert.respository.FwUserDivisionRespository;
import com.css.zfzx.fwsjcj.modules.group.entity.FwGroupEntity;
import com.css.zfzx.fwsjcj.modules.group.entity.FwGroupUserEntity;
import com.css.zfzx.fwsjcj.modules.group.repository.FwGroupRepository;
import com.css.zfzx.fwsjcj.modules.group.repository.FwGroupUserRepositoty;
import com.css.zfzx.fwsjcj.modules.structure.entity.FwStructureFormEntity;
import com.css.zfzx.fwsjcj.modules.structure.repository.FwStructureFormRepositoryQueryRepository;
import com.css.zfzx.fwsjcj.modules.structure.vo.StructureQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author leon
 * @Title: FwStoneStructureRepository
 * @Description: 石结构
 * @date 2020/6/4 14:27
 */
@Repository
@PropertySource("classpath:platform-config.yml")
public class FwStructureFormRepositoryQueryImpl implements FwStructureFormRepositoryQueryRepository {
    @Autowired
    EntityManager entityManager;
    @Value("${role.superCode}")
    private String superCode;
    @Value("${role.provinceCode}")
    private String provinceCode;
    @Value("${role.cityCode}")
    private String cityCode;
    @Value("${role.areaCode}")
    private String areaCode;//县管理员编号
    @Value("${role.xcCollectCode}")
    private String xcCollectCode;//详查采集员
    @Value("${role.dataCollectCode}")
    private String dataCollectCode;
    @Autowired
    private DivisionRepository divisionRepository;
    @Autowired
    private FwUserDivisionRespository fwUserDivisionRespository;
    @Autowired
    FwGroupRepository fwGroupRepository;
    @Autowired
    FwGroupUserRepositoty fwGroupUserRepositoty;

    @Override
    public Page<FwStructureFormEntity> getSructFormPage(StructureQueryVo structureQueryVo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder(" select * from fw_structure_form");
        StringBuilder whereSql = new StringBuilder(" where del_flag = " + Constant.IS_VALID_YES);
        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
            whereSql.append(" and task_id =:taskId");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            whereSql.append(" and status =:status");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())){
            whereSql.append(" and belongto_province like :belongtoProvince");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())){
            whereSql.append(" and belongto_city like :belongtoCity");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())){
            whereSql.append(" and belongto_area like :belongtoArea");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getTaskName())){
            whereSql.append(" and task_name like :taskName");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getStructureType())){
            whereSql.append(" and structure_type =:structureType");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getStructureNum())){
            whereSql.append(" and structure_num =:structureNum");
        }
        StringBuilder orderBy = new StringBuilder(" order by create_time desc");
        javax.persistence.Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(orderBy).toString(), FwStructureFormEntity.class);
        StringBuilder countSql = new StringBuilder(" select count(*) from fw_structure_form");
        Query countQuery = entityManager.createNativeQuery(countSql.append(whereSql).toString());
        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
            nativeQuery.setParameter("taskId", structureQueryVo.getTaskId());
            countQuery.setParameter("taskId", structureQueryVo.getTaskId());
        }
        if (!StringUtils.isEmpty(structureQueryVo.getTaskName())) {
            nativeQuery.setParameter("taskName", "%"+structureQueryVo.getTaskName()+"%");
            countQuery.setParameter("taskName", "%"+structureQueryVo.getTaskName()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())) {
            nativeQuery.setParameter("belongtoProvince", "%"+structureQueryVo.getBelongtoProvince()+"%");
            countQuery.setParameter("belongtoProvince", "%"+structureQueryVo.getBelongtoProvince()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())) {
            nativeQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
            countQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())) {
            nativeQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
            countQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStructureType())) {
            nativeQuery.setParameter("structureType", structureQueryVo.getStructureType());
            countQuery.setParameter("structureType", structureQueryVo.getStructureType());
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            nativeQuery.setParameter("status", structureQueryVo.getStatus());
            countQuery.setParameter("status", structureQueryVo.getStatus());
        }
        if(!StringUtils.isEmpty(structureQueryVo.getStructureNum())){
            nativeQuery.setParameter("structureNum", structureQueryVo.getStructureNum());
            countQuery.setParameter("structureNum", structureQueryVo.getStructureNum());
        }
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        nativeQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        nativeQuery.setMaxResults(pageable.getPageSize());
        List<FwStructureFormEntity> resultList = nativeQuery.getResultList();
        BigInteger countNum = (BigInteger) countQuery.getSingleResult();
        Page<FwStructureFormEntity> page = new PageImpl<>(resultList, pageable, countNum.longValue());
        return page;
    }

    @Override
    public Page<FwStructureFormEntity> getCheckPage(String role,StructureQueryVo structureQueryVo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder(" select * from fw_structure_form");
        StringBuilder whereSql = new StringBuilder(" where del_flag = " + Constant.IS_VALID_YES);
        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
            whereSql.append(" and task_id =:taskId");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            whereSql.append(" and status =:status");
        }
        /**
         * 登录用户查询权限限制
         */
        String userId = PlatformSessionUtils.getUserId();

        if ("1".equals(role)){
            if(!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())){
                whereSql.append(" and belongto_province like :belongtoProvince");
            }
            if(!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())){
                whereSql.append(" and belongto_city like :belongtoCity");
            }
            if(!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())){
                whereSql.append(" and belongto_area like :belongtoArea");
            }
        }
        if ("2".equals(role)){
            whereSql.append(" and belongto_province like :belongtoProvince");
            if(!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())){
                whereSql.append(" and belongto_city like :belongtoCity");
            }
            if(!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())){
                whereSql.append(" and belongto_area like :belongtoArea");
            }
        }
        if ("3".equals(role)){
            whereSql.append(" and belongto_province like :belongtoProvince");
            whereSql.append(" and belongto_city like :belongtoCity");
            if(!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())){
                whereSql.append(" and belongto_area like :belongtoArea");
            }
        }
        if ("4".equals(role)){
            whereSql.append(" and belongto_province like :belongtoProvince");
            whereSql.append(" and belongto_city like :belongtoCity");
            whereSql.append(" and belongto_area like :belongto_area");
        }
        if ("6".equals(role)){
            whereSql.append(" and create_user in :listUser");
        }
        if (PlatformObjectUtils.isEmpty(role)){
            whereSql.append(" and create_user =:userId");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getCheckStatus())){
            if ("0".equals(structureQueryVo.getCheckStatus())){
                whereSql.append(" and super_back_opinion is not null and super_back_opinion != ''");
            }else if ("1".equals(structureQueryVo.getCheckStatus())){
                whereSql.append(" and province_back_opinion is not null and province_back_opinion != ''");
            }
        }

        if(!StringUtils.isEmpty(structureQueryVo.getTaskName())){
            whereSql.append(" and task_name like :taskName");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getStructureNum())){
            whereSql.append(" and structure_num like :structureNum");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBuildingName())){
            whereSql.append(" and building_name like :buildingName");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getCollectUser())){
            whereSql.append(" and collect_user like :collectUser");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getStructureType())){
            whereSql.append(" and structure_type =:structureType");
        }
        whereSql.append(" and status !=0");
        StringBuilder orderBy = new StringBuilder(" order by create_time desc");
        javax.persistence.Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(orderBy).toString(), FwStructureFormEntity.class);
        StringBuilder countSql = new StringBuilder(" select count(*) from fw_structure_form");
        Query countQuery = entityManager.createNativeQuery(countSql.append(whereSql).toString());
        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
            nativeQuery.setParameter("taskId", structureQueryVo.getTaskId());
            countQuery.setParameter("taskId", structureQueryVo.getTaskId());
        }
        if (!StringUtils.isEmpty(structureQueryVo.getTaskName())) {
            nativeQuery.setParameter("taskName", "%"+structureQueryVo.getTaskName()+"%");
            countQuery.setParameter("taskName", "%"+structureQueryVo.getTaskName()+"%");
        }
        //省市县条件 赋值
        UserAPI userAPI = PlatformAPI.getOrgAPI().getUserAPI();
        DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
        String divisionId = mainDept.getDivisionId();
        DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);

        if ("1".equals(role)){
            if (!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())) {
                nativeQuery.setParameter("belongtoProvince", "%"+structureQueryVo.getBelongtoProvince()+"%");
                countQuery.setParameter("belongtoProvince", "%"+structureQueryVo.getBelongtoProvince()+"%");
            }
            if (!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())) {
                nativeQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
                countQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
            }
            if (!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())) {
                nativeQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
                countQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
            }
        }
        if ("2".equals(role)){
            List<String> list = Arrays.asList(validDivisionById.getAllParentId().split(","));
            divisionId = list.get(1);
            DivisionEntity divisionEntity = divisionRepository.findValidDivisionById(divisionId);
            String divisionName = divisionEntity.getDivisionName();
            nativeQuery.setParameter("belongtoProvince", "%"+divisionName+"%");
            countQuery.setParameter("belongtoProvince", "%"+divisionName+"%");
            if (!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())) {
                nativeQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
                countQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
            }
            if (!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())) {
                nativeQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
                countQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
            }
        }
        if ("3".equals(role)){
            List<String> list = Arrays.asList(validDivisionById.getAllParentId().split(","));
            divisionId = list.get(1);
            DivisionEntity divisionEntity = divisionRepository.findValidDivisionById(divisionId);
            String divisionName = divisionEntity.getDivisionName();
            nativeQuery.setParameter("belongtoProvince", "%"+divisionName+"%");
            countQuery.setParameter("belongtoProvince", "%"+divisionName+"%");
            divisionId = list.get(2);
            divisionEntity = divisionRepository.findValidDivisionById(divisionId);
            divisionName = divisionEntity.getDivisionName();
            nativeQuery.setParameter("belongtoCity", "%"+divisionName+"%");
            countQuery.setParameter("belongtoCity", "%"+divisionName+"%");
            if (!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())) {
                nativeQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
                countQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
            }
        }
        if ("4".equals(role)){
            List<String> list = Arrays.asList(validDivisionById.getAllParentId().split(","));
            divisionId = list.get(1);
            DivisionEntity divisionEntity = divisionRepository.findValidDivisionById(divisionId);
            String divisionName = divisionEntity.getDivisionName();
            nativeQuery.setParameter("belongtoProvince", "%"+divisionName+"%");
            countQuery.setParameter("belongtoProvince", "%"+divisionName+"%");
            divisionId = list.get(2);
            divisionEntity = divisionRepository.findValidDivisionById(divisionId);
            divisionName = divisionEntity.getDivisionName();
            nativeQuery.setParameter("belongtoCity", "%"+divisionName+"%");
            countQuery.setParameter("belongtoCity", "%"+divisionName+"%");
            divisionId = list.get(3);
            divisionEntity = divisionRepository.findValidDivisionById(divisionId);
            divisionName = divisionEntity.getDivisionName();
            nativeQuery.setParameter("belongtoArea", "%"+divisionName+"%");
            countQuery.setParameter("belongtoArea", "%"+divisionName+"%");
        }
        if ("6".equals(role)){
            //组长
            List<String> listGroup = new ArrayList<>();
            List<FwGroupEntity> byGroupLeaderId = fwGroupRepository.findAllByGroupLeaderId(userId);
            byGroupLeaderId.forEach(fwGroupEntity -> {
                listGroup.add(fwGroupEntity.getId());
            });
            List<List<FwGroupUserEntity>> lists = new ArrayList<>();
            listGroup.forEach(s -> {
                lists.add(fwGroupUserRepositoty.findAllByGroupId(s));
            });
            List<String> listUser = new ArrayList<>();
            for (List<FwGroupUserEntity> listU : lists) {
                for (FwGroupUserEntity fw : listU) {
                    listUser.add(fw.getUserId());
                }
            }
            listUser.add(userId);
            //利用jdk8特性对list进行去重
            List<String> listUserId = listUser.stream().distinct().collect(Collectors.toList());
            nativeQuery.setParameter("listUser", listUserId);
            countQuery.setParameter("listUser", listUserId);
        }
        if (PlatformObjectUtils.isEmpty(role)){
            nativeQuery.setParameter("userId", userId);
            countQuery.setParameter("userId", userId);
        }


        if (!StringUtils.isEmpty(structureQueryVo.getStructureNum())) {
            nativeQuery.setParameter("structureNum", "%"+structureQueryVo.getStructureNum()+"%");
            countQuery.setParameter("structureNum", "%"+structureQueryVo.getStructureNum()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getBuildingName())) {
            nativeQuery.setParameter("buildingName", "%"+structureQueryVo.getBuildingName()+"%");
            countQuery.setParameter("buildingName", "%"+structureQueryVo.getBuildingName()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getCollectUser())) {
            nativeQuery.setParameter("collectUser", "%"+structureQueryVo.getCollectUser()+"%");
            countQuery.setParameter("collectUser", "%"+structureQueryVo.getCollectUser()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStructureType())) {
            nativeQuery.setParameter("structureType", structureQueryVo.getStructureType());
            countQuery.setParameter("structureType", structureQueryVo.getStructureType());
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            nativeQuery.setParameter("status", structureQueryVo.getStatus());
            countQuery.setParameter("status", structureQueryVo.getStatus());
        }
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        nativeQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        nativeQuery.setMaxResults(pageable.getPageSize());
        List<FwStructureFormEntity> resultList = nativeQuery.getResultList();
        BigInteger countNum = (BigInteger) countQuery.getSingleResult();
        Page<FwStructureFormEntity> page = new PageImpl<>(resultList, pageable, countNum.longValue());
        return page;

    }

    @Override
    public Page<FwStructureFormEntity> getCheckForQgSiftPage(StructureQueryVo structureQueryVo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder(" select * from fw_structure_form");
        StringBuilder whereSql = new StringBuilder(" where del_flag = " + Constant.IS_VALID_YES);
//        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
//            whereSql.append(" and task_id =:taskId");
//        }
        /**
         * 登录用户查询权限限制
         */
        String userId = PlatformSessionUtils.getUserId();
        // 获取当前登录用户角色
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        // 角色列表里面是否包含三个管理员
        boolean containtSuperRole = ServerUtil.isContaintRole(roles, superCode);
        boolean containtProRole = ServerUtil.isContaintRole(roles, provinceCode);

       //if(containtSuperRole){
            //超级用户，查询所有
            whereSql.append("");
//        }else if(containtProRole){
//            //查询自己所属省
//            whereSql.append(" and belongto_province =:belongtoProvince");
//        }else{
//            //查询自己所属省
//            whereSql.append(" and belongto_province =:belongtoProvince");
//        }

        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())){
            whereSql.append(" and belongto_province like :belongtoProvince");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())){
            whereSql.append(" and belongto_city like :belongtoCity");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())){
            whereSql.append(" and belongto_area like :belongtoArea");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getTaskName())){
            whereSql.append(" and task_name like :taskName");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getStructureType())){
            whereSql.append(" and structure_type =:structureType");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            whereSql.append(" and status =:status");
        }
        whereSql.append(" and status !='0'");
        StringBuilder orderBy = new StringBuilder(" order by create_time desc");
        javax.persistence.Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(orderBy).toString(), FwStructureFormEntity.class);
        StringBuilder countSql = new StringBuilder(" select count(*) from fw_structure_form");
        Query countQuery = entityManager.createNativeQuery(countSql.append(whereSql).toString());
//        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
//            nativeQuery.setParameter("taskId", structureQueryVo.getTaskId());
//            countQuery.setParameter("taskId", structureQueryVo.getTaskId());
//        }

//        if(containtSuperRole){
//            //什么条件也不加
//        }else{
//            DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
//            String divisionId = mainDept.getDivisionId();
//            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
//            String divisionName = validDivisionById.getDivisionName();
//            nativeQuery.setParameter("belongtoProvince", divisionName);
//            countQuery.setParameter("belongtoProvince", divisionName);
//        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())) {
            nativeQuery.setParameter("belongtoProvince", "%"+structureQueryVo.getBelongtoProvince()+"%");
            countQuery.setParameter("belongtoProvince", "%"+structureQueryVo.getBelongtoProvince()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())) {
            nativeQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
            countQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())) {
            nativeQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
            countQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
        }

        if (!StringUtils.isEmpty(structureQueryVo.getStructureType())) {
            nativeQuery.setParameter("structureType", structureQueryVo.getStructureType());
            countQuery.setParameter("structureType", structureQueryVo.getStructureType());
        }
        if (!StringUtils.isEmpty(structureQueryVo.getTaskName())) {
            nativeQuery.setParameter("taskName", "%"+structureQueryVo.getTaskName()+"%");
            countQuery.setParameter("taskName", "%"+structureQueryVo.getTaskName()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            nativeQuery.setParameter("status", structureQueryVo.getStatus());
            countQuery.setParameter("status", structureQueryVo.getStatus());
        }
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        nativeQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        nativeQuery.setMaxResults(pageable.getPageSize());
        List<FwStructureFormEntity> resultList = nativeQuery.getResultList();
        BigInteger countNum = (BigInteger) countQuery.getSingleResult();
        Page<FwStructureFormEntity> page = new PageImpl<>(resultList, pageable, countNum.longValue());
        return page;
    }

    @Override
    public Page<FwStructureFormEntity> checkForExpertSift(StructureQueryVo structureQueryVo, int curPage, int pageSize) {
       /* List<String> provinceList=new ArrayList<>(40);*/
        List<String> cityList=new ArrayList<>(40);
        StringBuilder sql = new StringBuilder(" select * from fw_structure_form");
        StringBuilder whereSql = new StringBuilder(" where del_flag = " + Constant.IS_VALID_YES);
//        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
//            whereSql.append(" and task_id =:taskId");
//        }
        /**
         * 登录用户查询权限限制
         */
        String userId = PlatformSessionUtils.getUserId();
        // 获取当前登录用户角色
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        // 角色列表里面是否包含三个管理员
        boolean containtSuperRole = ServerUtil.isContaintRole(roles, superCode);
        boolean containtProRole = ServerUtil.isContaintRole(roles, provinceCode);

        //if(containtSuperRole){
        //超级用户，查询所有
        whereSql.append("");
//        }else if(containtProRole){
//            //查询自己所属省
//            whereSql.append(" and belongto_province =:belongtoProvince");
//        }else{
//            //查询自己所属省
//            whereSql.append(" and belongto_province =:belongtoProvince");
//        }

        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())){
            whereSql.append(" and belongto_province like :belongtoProvince");
        }/*else{
            //查询所有的省
            whereSql.append(" and belongto_province in (:belongtoProvince)");
        }*/
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())){
            whereSql.append(" and belongto_city like :belongtoCity");
        }else{
            List<RoleEntity> role = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
            System.out.println(role);
            for(RoleEntity item:role){
                if(item.getRoleName().lastIndexOf("专家")!=-1){
                    whereSql.append(" and (belongto_city in (:belongtoCity) or belongto_area in (:belongtoCity))");
                }
            }
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())){
            whereSql.append(" and belongto_area like :belongtoArea");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getStructureType())){
            whereSql.append(" and structure_type in (:structureType)");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            whereSql.append(" and status =:status");
        }
        whereSql.append(" and status !='0'");
        StringBuilder orderBy = new StringBuilder(" order by create_time desc");
        javax.persistence.Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(orderBy).toString(), FwStructureFormEntity.class);
        StringBuilder countSql = new StringBuilder(" select count(*) from fw_structure_form");
        Query countQuery = entityManager.createNativeQuery(countSql.append(whereSql).toString());
//        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
//            nativeQuery.setParameter("taskId", structureQueryVo.getTaskId());
//            countQuery.setParameter("taskId", structureQueryVo.getTaskId());
//        }

//        if(containtSuperRole){
//            //什么条件也不加
//        }else{
//            DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
//            String divisionId = mainDept.getDivisionId();
//            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
//            String divisionName = validDivisionById.getDivisionName();
//            nativeQuery.setParameter("belongtoProvince", divisionName);
//            countQuery.setParameter("belongtoProvince", divisionName);
//        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())) {
            nativeQuery.setParameter("belongtoProvince", "%"+structureQueryVo.getBelongtoProvince()+"%");
            countQuery.setParameter("belongtoProvince", "%"+structureQueryVo.getBelongtoProvince()+"%");
        }/*else{
            //查询所有的省
            List<Map<String, Object>> province = fwUserDivisionRespository.getProvince(userId);

            if(province!=null){
                for(Map<String, Object> item:province){
                    String divisionName = (String) item.get("divisionName");
                    provinceList.add(divisionName);
                }
            }
            nativeQuery.setParameter("belongtoProvince", provinceList);
            countQuery.setParameter("belongtoProvince", provinceList);
        }*/
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())) {
            nativeQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
            countQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
        }else{
            List<RoleEntity> role = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
            System.out.println(role);
            for(RoleEntity item:role){
                if(item.getRoleName().lastIndexOf("专家")!=-1){
                    //查询省的对应市
                    List<Map<String, Object>> city = fwUserDivisionRespository.getCity(userId);
                    if(city!=null){
                        for(Map<String, Object> item1:city){
                            String divisionName = (String) item1.get("divisionName");
                            cityList.add(divisionName);
                        }
                    }
                    nativeQuery.setParameter("belongtoCity", cityList);
                    countQuery.setParameter("belongtoCity", cityList);
                }
            }
        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())) {
            nativeQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
            countQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStructureType())) {
            String[] split = structureQueryVo.getStructureType().split(",");
            List structureType=new ArrayList();
            for(int a=0;a<split.length;a++){
                structureType.add(split[a]);
            }
            nativeQuery.setParameter("structureType", structureType);
            countQuery.setParameter("structureType", structureType);
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            nativeQuery.setParameter("status", structureQueryVo.getStatus());
            countQuery.setParameter("status", structureQueryVo.getStatus());
        }
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        nativeQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        nativeQuery.setMaxResults(pageable.getPageSize());
        List<FwStructureFormEntity> resultList = nativeQuery.getResultList();
        BigInteger countNum = (BigInteger) countQuery.getSingleResult();
        Page<FwStructureFormEntity> page = new PageImpl<>(resultList, pageable, countNum.longValue());
        return page;
    }

    @Override
    public List<String> getIds(StructureQueryVo structureQueryVo) {
        StringBuilder countSql = new StringBuilder(" SELECT a.structure_id from fw_structure_form a ");
        StringBuilder whereSql = new StringBuilder(" where a.del_flag = " + Constant.IS_VALID_YES);
        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
            whereSql.append(" and a.task_id =:taskId");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            whereSql.append(" and a.status =:status");
        }

        /**
         * 登录用户查询权限限制
         */
        String userId = PlatformSessionUtils.getUserId();
        // 获取当前登录用户角色
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        // 角色列表里面是否包含三个管理员
        boolean containtSuperRole = ServerUtil.isContaintRole(roles, superCode);
        boolean containtProRole = ServerUtil.isContaintRole(roles, provinceCode);
        boolean containtCityRole = ServerUtil.isContaintRole(roles, cityCode);
        if(!containtSuperRole){
            if(!containtProRole & !containtCityRole){
                whereSql.append(" and a.create_user =:userId");
            }else if(containtProRole){
                whereSql.append(" and a.belongto_province like :belongtoProvince");
            }else if(containtCityRole){
                whereSql.append(" and a.belongto_city like :belongtoCity");
            }

        }
        if (!StringUtils.isEmpty(structureQueryVo.getCheckStatus())) {
            if ("0".equals(structureQueryVo.getCheckStatus())){
                whereSql.append(" and a.super_back_opinion is not null and a.super_back_opinion != ''");

            } else if ("1".equals(structureQueryVo.getCheckStatus())){
                whereSql.append(" and a.province_back_opinion is not null and a.province_back_opinion != ''");
            }
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())){
            whereSql.append(" and a.belongto_province like :belongtoProvince");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())){
            whereSql.append(" and a.belongto_city like :belongtoCity");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())){
            whereSql.append(" and a.belongto_area like :belongtoArea");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getTaskName())){
            whereSql.append(" and a.task_name like :taskName");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getStructureNum())){
            whereSql.append(" and a.structure_num like :structureNum");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBuildingName())){
            whereSql.append(" and a.building_name like :buildingName");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getCollectUser())){
            whereSql.append(" and a.collect_user like :collectUser");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getStructureType())){
            whereSql.append(" and a.structure_type =:structureType");
        }
        whereSql.append(" and a.status !=0");
        StringBuilder orderBy = new StringBuilder(" order by a.create_time desc");
        Query countQuery = entityManager.createNativeQuery(countSql.append(whereSql).toString());
        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
            countQuery.setParameter("taskId", structureQueryVo.getTaskId());
        }
        if (!StringUtils.isEmpty(structureQueryVo.getTaskName())) {
            countQuery.setParameter("taskName", "%"+structureQueryVo.getTaskName()+"%");
        }
        if(!containtSuperRole){
            if(!containtProRole & !containtCityRole){
                countQuery.setParameter("userId", userId);
            }else if(containtProRole){
                // 获取当前用户的行政区域
                UserAPI userAPI = PlatformAPI.getOrgAPI().getUserAPI();
                DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
                String divisionId = mainDept.getDivisionId();
                DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
                String divisionName = validDivisionById.getDivisionName();
                countQuery.setParameter("belongtoProvince", "%"+divisionName+"%");
            }else if(containtCityRole){
                // 获取当前用户的行政区域
                DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
                String divisionId = mainDept.getDivisionId();
                DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
                String divisionName = validDivisionById.getDivisionName();
                countQuery.setParameter("belongtoCity", "%"+divisionName+"%");
            }

        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())) {
            countQuery.setParameter("belongtoProvince", "%"+structureQueryVo.getBelongtoProvince()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())) {
            countQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())) {
            countQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
        }

        if (!StringUtils.isEmpty(structureQueryVo.getStructureNum())) {
            countQuery.setParameter("structureNum", "%"+structureQueryVo.getStructureNum()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getBuildingName())) {
            countQuery.setParameter("buildingName", "%"+structureQueryVo.getBuildingName()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getCollectUser())) {
            countQuery.setParameter("collectUser", "%"+structureQueryVo.getCollectUser()+"%");
        }

        if (!StringUtils.isEmpty(structureQueryVo.getStructureType())) {
            countQuery.setParameter("structureType", structureQueryVo.getStructureType());
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            countQuery.setParameter("status", structureQueryVo.getStatus());
        }
        List<String> ids = countQuery.getResultList();
        return ids;
    }

    @Override
    public List<String> getExpertIds(StructureQueryVo structureQueryVo) {
        if(structureQueryVo.getBelongtoProvince().equals("null")){
            structureQueryVo.setBelongtoProvince("");
        }
        if(structureQueryVo.getBelongtoCity().equals("null")){
            structureQueryVo.setBelongtoCity("");
        }
        if(structureQueryVo.getBelongtoArea().equals("null")){
            structureQueryVo.setBelongtoArea("");
        }
        if(structureQueryVo.getStatus().equals("null")){
            structureQueryVo.setStatus("");
        }
        /* List<String> provinceList=new ArrayList<>(40);*/
        List<String> cityList=new ArrayList<>(40);
        StringBuilder sql = new StringBuilder(" select * from fw_structure_form");
        StringBuilder whereSql = new StringBuilder(" where del_flag = " + Constant.IS_VALID_YES);
//        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
//            whereSql.append(" and task_id =:taskId");
//        }
        /**
         * 登录用户查询权限限制
         */
        String userId = PlatformSessionUtils.getUserId();
        // 获取当前登录用户角色
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        // 角色列表里面是否包含三个管理员
        boolean containtSuperRole = ServerUtil.isContaintRole(roles, superCode);
        boolean containtProRole = ServerUtil.isContaintRole(roles, provinceCode);

        //if(containtSuperRole){
        //超级用户，查询所有
        whereSql.append("");
//        }else if(containtProRole){
//            //查询自己所属省
//            whereSql.append(" and belongto_province =:belongtoProvince");
//        }else{
//            //查询自己所属省
//            whereSql.append(" and belongto_province =:belongtoProvince");
//        }

        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())){
            whereSql.append(" and belongto_province like :belongtoProvince");
        }/*else{
            //查询所有的省
            whereSql.append(" and belongto_province in (:belongtoProvince)");
        }*/
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())){
            whereSql.append(" and belongto_city like :belongtoCity");
        }else{
            List<RoleEntity> role = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
            System.out.println(role);
            for(RoleEntity item:role){
                if(item.getRoleName().lastIndexOf("专家")!=-1){
                    whereSql.append(" and (belongto_city in (:belongtoCity) or belongto_area in (:belongtoCity))");
                }
            }
        }
        if(!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())){
            whereSql.append(" and belongto_area like :belongtoArea");
        }
        if(!StringUtils.isEmpty(structureQueryVo.getStructureType())){
            whereSql.append(" and structure_type in (:structureType)");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            whereSql.append(" and status =:status");
        }
        whereSql.append(" and status !='0'");
        StringBuilder orderBy = new StringBuilder(" order by create_time desc");
        javax.persistence.Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(orderBy).toString(), FwStructureFormEntity.class);
   /*     StringBuilder countSql = new StringBuilder(" select count(*) from fw_structure_form");
        Query countQuery = entityManager.createNativeQuery(countSql.append(whereSql).toString());*/
//        if (!StringUtils.isEmpty(structureQueryVo.getTaskId())) {
//            nativeQuery.setParameter("taskId", structureQueryVo.getTaskId());
//         //   countQuery.setParameter("taskId", structureQueryVo.getTaskId());
//        }

//        if(containtSuperRole){
//            //什么条件也不加
//        }else{
//            DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
//            String divisionId = mainDept.getDivisionId();
//            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
//            String divisionName = validDivisionById.getDivisionName();
//            nativeQuery.setParameter("belongtoProvince", divisionName);
//          //  countQuery.setParameter("belongtoProvince", divisionName);
//        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoProvince())) {
            nativeQuery.setParameter("belongtoProvince", "%"+structureQueryVo.getBelongtoProvince()+"%");
          //  countQuery.setParameter("belongtoProvince", "%"+structureQueryVo.getBelongtoProvince()+"%");
        }/*else{
            //查询所有的省
            List<Map<String, Object>> province = fwUserDivisionRespository.getProvince(userId);

            if(province!=null){
                for(Map<String, Object> item:province){
                    String divisionName = (String) item.get("divisionName");
                    provinceList.add(divisionName);
                }
            }
            nativeQuery.setParameter("belongtoProvince", provinceList);
            //countQuery.setParameter("belongtoProvince", provinceList);
        }*/
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoCity())) {
            nativeQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
           // countQuery.setParameter("belongtoCity", "%"+structureQueryVo.getBelongtoCity()+"%");
        }else{
            List<RoleEntity> role = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
            System.out.println(role);
            for(RoleEntity item:role){
                if(item.getRoleName().lastIndexOf("专家")!=-1){
                    //查询省的对应市
                    List<Map<String, Object>> city = fwUserDivisionRespository.getCity(userId);
                    if(city!=null){
                        for(Map<String, Object> item1:city){
                            String divisionName = (String) item1.get("divisionName");
                            cityList.add(divisionName);
                        }
                    }
                    nativeQuery.setParameter("belongtoCity", cityList);
                  //  countQuery.setParameter("belongtoCity", cityList);
                }
            }
        }
        if (!StringUtils.isEmpty(structureQueryVo.getBelongtoArea())) {
            nativeQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
            //countQuery.setParameter("belongtoArea", "%"+structureQueryVo.getBelongtoArea()+"%");
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStructureType())) {
            String[] split = structureQueryVo.getStructureType().split(",");
            List structureType=new ArrayList();
            for(int a=0;a<split.length;a++){
                structureType.add(split[a]);
            }
            nativeQuery.setParameter("structureType", structureType);
          //  countQuery.setParameter("structureType", structureType);
        }
        if (!StringUtils.isEmpty(structureQueryVo.getStatus())) {
            nativeQuery.setParameter("status", structureQueryVo.getStatus());
            //countQuery.setParameter("status", structureQueryVo.getStatus());
        }
        List<FwStructureFormEntity> resultList = nativeQuery.getResultList();
        List<String> ids = resultList.stream().map(entity -> entity.getStructureId()).collect(Collectors.toList());
        return ids;
    }

    @Override
    public Map<String, Integer> getBelongtoProvince(String province, String city,String area) {
        Integer provinceCount = 0;
        Integer cityCount = 0;
        Integer areaCount = 0;
        Map<String, Integer> countMap = new HashMap<>();
        StringBuilder sql = new StringBuilder("select count(*) from fw_structure_form where del_flag = '0'");
        if (StringUtils.isEmpty(province) && StringUtils.isEmpty(city) && StringUtils.isEmpty(area)){
            StringBuilder wheresql = new StringBuilder(" and belongto_province is not null");
            StringBuilder orderBy = new StringBuilder(" GROUP BY belongto_province");
            Query nativeQuery = entityManager.createNativeQuery(sql.append(wheresql).append(orderBy).toString());
            List provinceList = nativeQuery.getResultList();
            provinceCount = provinceList.size();

            sql = new StringBuilder("select count(*) from fw_structure_form where del_flag = '0'");
            wheresql = new StringBuilder(" and belongto_province is not null and belongto_city is not null");
            orderBy = new StringBuilder(" GROUP BY belongto_province,belongto_city");
            nativeQuery = entityManager.createNativeQuery(sql.append(wheresql).append(orderBy).toString());
            List cityList = nativeQuery.getResultList();
            cityCount = cityList.size();

            sql = new StringBuilder("select count(*) from fw_structure_form where del_flag = '0'");
            wheresql = new StringBuilder(" and belongto_province is not null and belongto_city is not null and belongto_area is not null ");
            orderBy = new StringBuilder(" GROUP BY belongto_province,belongto_city,belongto_area");
            nativeQuery = entityManager.createNativeQuery(sql.append(wheresql).append(orderBy).toString());
            List areaList = nativeQuery.getResultList();
            areaCount = areaList.size();
        }
        if (!StringUtils.isEmpty(province) && StringUtils.isEmpty(city) && StringUtils.isEmpty(area)){
            StringBuilder wheresql = new StringBuilder(" and belongto_province = '" + province + "' and belongto_city is not null");
            StringBuilder orderBy = new StringBuilder(" GROUP BY belongto_province,belongto_city");
            Query nativeQuery = entityManager.createNativeQuery(sql.append(wheresql).append(orderBy).toString());
            List cityList = nativeQuery.getResultList();
            cityCount = cityList.size();

            sql = new StringBuilder("select count(*) from fw_structure_form where del_flag = '0'");
            wheresql = new StringBuilder(" and belongto_province = '" + province + "' and belongto_city is not null and belongto_area is not null ");
            orderBy = new StringBuilder(" GROUP BY belongto_province,belongto_city,belongto_area");
            nativeQuery = entityManager.createNativeQuery(sql.append(wheresql).append(orderBy).toString());
            List areaList = nativeQuery.getResultList();
            areaCount = areaList.size();
        }
        if (!StringUtils.isEmpty(province) && !StringUtils.isEmpty(city) && StringUtils.isEmpty(area)){
            StringBuilder wheresql = new StringBuilder("  and belongto_province = '" + province + "' and belongto_city = '"+ city +"' and belongto_area is not null ");
            StringBuilder orderBy = new StringBuilder(" GROUP BY belongto_province,belongto_city,belongto_area");
            Query nativeQuery = entityManager.createNativeQuery(sql.append(wheresql).append(orderBy).toString());
            List areaList = nativeQuery.getResultList();
            areaCount = areaList.size();
        }
        countMap.put("provinceCount",provinceCount);
        countMap.put("cityCount",cityCount);
        countMap.put("areaCount",areaCount);
        return countMap;
    }
}
